'use strict';

// 云对象名：learning-service
module.exports = {
  /**
   * 获取规则列表
   * @param {string|object} params - 参数对象或action字符串
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} category - 分类
   * @param {string} subcategory - 二级分类
   * @param {string} keyword - 关键词
   * @param {string} creatorId - 创建者ID
   * @returns {object} 规则列表
   */
  async getRuleList(params, page = 1, limit = 10, category, subcategory, keyword, creatorId) {
    const db = uniCloud.database();
    
    // 兼容处理：支持对象参数和位置参数两种方式
    let action = 'list';
    if (typeof params === 'object' && params !== null) {
      // 对象参数方式
      action = params.action || 'list';
      page = params.page || 1;
      limit = params.limit || 10;
      category = params.category;
      subcategory = params.subcategory;
      keyword = params.keyword;
      creatorId = params.creatorId;
    } else if (typeof params === 'string') {
      // 位置参数方式（向后兼容）
      action = params;
    }
    
    try {
      // 如果是获取管理员发布的规则
      if (action === 'getMyPublishedRules' && creatorId) {
        return await this._getMyPublishedRules(db, creatorId, page, limit, keyword, category, subcategory);
      }
      
      // 构建查询条件
      const where = {};
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 添加二级分类筛选
      if (subcategory && subcategory !== '全部') {
        where.subcategory = subcategory;
      }
      
      // 添加关键词搜索
      if (keyword) {
        where.$or = [
          { title: db.command.regExp({ regexp: keyword, options: 'i' }) },
          { content: db.command.regExp({ regexp: keyword, options: 'i' }) }
        ];
      }
      
      // 只获取已发布的规则
      where.status = 'published';
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询规则列表
      const rulesResult = await db.collection('rule_contents')
        .where(where)
        .field({
          _id: true,
          title: true,
          category: true,
          subcategory: true,
          tags: true,
          view_count: true,
          create_date: true,
          update_date: true,
          status: true,
          author_id: true,
          author_name: true
        })
        .orderBy('create_date', 'asc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('rule_contents')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: rulesResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取规则列表失败:', error);
      return {
        code: -1,
        message: '获取规则列表失败: ' + error.message
      };
    }
  },

  /**
   * 获取规则详情
   * @param {string|object} params - 规则ID或参数对象
   * @param {string} params.ruleId - 规则ID
   * @param {string} params.id - 规则ID（兼容字段）
   * @param {boolean} params.isAdmin - 是否为管理员访问
   * @returns {object} 规则详情
   */
  async getRuleDetail(params) {
    // 兼容处理：支持直接传入ruleId字符串或对象参数
    let ruleId, isAdmin = false;
    
    if (typeof params === 'string') {
      ruleId = params;
    } else if (typeof params === 'object' && params) {
      ruleId = params.ruleId || params.id;
      isAdmin = params.isAdmin || false;
    }
    
    if (!ruleId) {
      return {
        code: -1,
        message: '规则ID不能为空'
      };
    }

    try {
      const db = uniCloud.database();
      
      // 查询规则详情
      const ruleResult = await db.collection('rule_contents')
        .doc(ruleId)
        .get();
      
      if (!ruleResult.data || ruleResult.data.length === 0) {
        return {
          code: -1,
          message: '规则不存在'
        };
      }
      
      const ruleData = Array.isArray(ruleResult.data) ? ruleResult.data[0] : ruleResult.data;
      
      // 如果不是管理员访问，检查规则是否已发布
      if (!isAdmin && ruleData.status !== 'published') {
        return {
          code: -1,
          message: '规则不存在或未发布'
        };
      }
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          ruleDetail: ruleData
        }
      };
    } catch (error) {
      console.error('获取规则详情失败:', error);
      return {
        code: -1,
        message: '获取规则详情失败: ' + error.message
      };
    }
  },

  /**
   * 获取规则分类
   * @returns {object} 规则分类列表
   */
  async getRuleCategories() {
    try {
      const db = uniCloud.database();
      
      // 查询所有已发布规则的分类
      const categoriesResult = await db.collection('rule_contents')
        .where({
          status: 'published'
        })
        .field({
          category: true
        })
        .get();
      
      // 提取唯一分类
      const categories = [...new Set(categoriesResult.data.map(item => item.category).filter(Boolean))];
      
      return {
        code: 0,
        message: '获取成功',
        data: categories
      };
    } catch (error) {
      console.error('获取规则分类失败:', error);
      return {
        code: -1,
        message: '获取规则分类失败: ' + error.message
      };
    }
  },

  /**
   * 获取规则内容
   * @param {string} ruleId - 规则ID
   * @returns {object} 规则内容
   */
  async getRuleContents(ruleId) {
    if (!ruleId) {
      return {
        code: -1,
        message: '规则ID不能为空'
      };
    }

    try {
      const db = uniCloud.database();
      
      // 查询规则内容
      const ruleResult = await db.collection('rule_contents')
        .doc(ruleId)
        .field({
          title: true,
          content: true,
          category: true,
          create_date: true,
          update_date: true
        })
        .get();
      
      if (!ruleResult.data || ruleResult.data.length === 0) {
        return {
          code: -1,
          message: '规则不存在'
        };
      }
      
      const ruleData = Array.isArray(ruleResult.data) ? ruleResult.data[0] : ruleResult.data;
      
      return {
        code: 0,
        message: '获取成功',
        data: ruleData
      };
    } catch (error) {
      console.error('获取规则内容失败:', error);
      return {
        code: -1,
        message: '获取规则内容失败: ' + error.message
      };
    }
  },

  /**
   * 更新规则
   * @param {string} ruleId - 规则ID
   * @param {string} title - 标题
   * @param {string} content - 内容
   * @param {string} category - 分类
   * @param {string} status - 状态
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 更新结果
   */
  async updateRule(ruleId, title, content, category, status, userId, token) {
    try {
      const db = uniCloud.database();
      
      if (!ruleId) {
        return {
          code: -1,
          message: '规则ID不能为空'
        };
      }
      
      // 验证用户权限
      let currentUserId;
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        const tokenResult = await db.collection('users').where({
          token: token
        }).get();
        
        if (tokenResult.data && tokenResult.data.length > 0) {
          currentUserId = tokenResult.data[0]._id;
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 查询规则信息
      const ruleResult = await db.collection('rules').doc(ruleId).get();
      if (!ruleResult.data || ruleResult.data.length === 0) {
        return {
          code: -1,
          message: '规则不存在'
        };
      }
      
      const rule = Array.isArray(ruleResult.data) ? ruleResult.data[0] : ruleResult.data;
      
      // 检查权限
      if (rule.userId !== currentUserId && rule.creator_id !== currentUserId) {
        return {
          code: -1,
          message: '无权限修改此规则'
        };
      }
      
      // 准备更新数据
      const updateData = {
        update_date: new Date()
      };
      
      if (title) updateData.title = title;
      if (content) updateData.content = content;
      if (category) updateData.category = category;
      if (status) updateData.status = status;
      
      // 更新规则
      await db.collection('rules').doc(ruleId).update(updateData);
      
      return {
        code: 0,
        message: '更新成功'
      };
    } catch (error) {
      console.error('更新规则失败:', error);
      return {
        code: -1,
        message: '更新失败: ' + error.message
      };
    }
  },

  /**
   * 删除规则
   * @param {object} params - 参数对象
   * @param {string} params.ruleId - 规则ID
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {string} params.creatorId - 创建者ID
   * @returns {object} 删除结果
   */
  async deleteRule(params) {
    try {
      const db = uniCloud.database();
      
      // 参数解构
      const { ruleId, userId, token, creatorId } = params;
      
      if (!ruleId) {
        return {
          code: -1,
          message: '规则ID不能为空'
        };
      }
      
      // 验证用户身份和token
      let currentUserId = '';
      
      if (userId || creatorId) {
        currentUserId = userId || creatorId;
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
          token: token
          });
        
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }
      
      if (!currentUserId) {
        return {
          code: 401,
          message: '用户未认证'
        };
      }
      
      // 查询规则信息
      const ruleResult = await db.collection('rule_contents').doc(ruleId).get();
      if (!ruleResult.data || ruleResult.data.length === 0) {
        return {
          code: -1,
          message: '规则不存在'
        };
      }
      
      const rule = Array.isArray(ruleResult.data) ? ruleResult.data[0] : ruleResult.data;
      
      // 检查权限
      if (rule.userId !== currentUserId && rule.creator_id !== currentUserId && rule.author_id !== currentUserId) {
        return {
          code: 403,
          message: '无权限删除此规则'
        };
      }
      
      // 软删除：更新状态为deleted
      await db.collection('rule_contents').doc(ruleId).update({
        status: 'deleted',
        delete_date: new Date()
      });
      
      return {
        code: 0,
        message: '删除成功'
      };
    } catch (error) {
      console.error('删除规则失败:', error);
      return {
        code: -1,
        message: '删除失败: ' + error.message
      };
    }
  },

  /**
   * 上传规则内容
   * @param {object} params - 参数对象
   * @param {string} params.title - 规则标题
   * @param {string} params.content - 规则内容
   * @param {string} params.category - 规则分类
   * @param {string} params.subcategory - 规则子分类
   * @param {array} params.tags - 规则标签
   * @param {string} params.version - 规则版本
   * @param {string} params.language - 语言
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {string} params.documentFileID - 文档文件ID
   * @param {object} params.userInfo - 用户信息
   * @returns {object} 上传结果
   */
  async uploadRuleContent(params) {
    try {
      const db = uniCloud.database();
      
      // 参数解构
      const { 
        title, 
        content, 
        category, 
        subcategory, 
        tags, 
        version, 
        language, 
        userId, 
        token, 
        documentFileID,
        userInfo 
      } = params;
      
      // 验证必填参数
      if (!title || !content) {
        return {
          code: -1,
          message: '标题和内容为必填项'
        };
      }
      
      // 验证用户身份和token
      let currentUserId = '';
      let currentUserInfo = null;
      
      if (userId) {
        currentUserId = userId;
        currentUserInfo = userInfo;
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
            token: token
          });
          
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
            currentUserInfo = tokenRes.userInfo;
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }
      
      // 验证用户ID
      if (!currentUserId) {
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }
      
      // 验证用户权限 - 检查是否为管理员
      if (currentUserInfo && currentUserInfo.role !== 4 && currentUserInfo.role !== '4') {
        return {
          code: 403,
          message: '权限不足，仅管理员可以发布规则'
        };
      }
      
      // 创建规则记录
      const ruleData = {
        title,
        content,
        category: category || '比赛规则',
        subcategory: subcategory || '',
        tags: Array.isArray(tags) ? tags : [],
        version: version || '1.0',
        language: language || 'zh-CN',
        document_url: documentFileID || '',
        create_date: new Date(),
        update_date: new Date(),
        userId: currentUserId,
        creator_id: currentUserId,
        author_id: currentUserId,
        view_count: 0,
        status: 'published'
      };
      
      const result = await db.collection('rule_contents').add(ruleData);
      
      return {
        code: 0,
        message: '规则发布成功',
        data: {
          id: result.id,
          ruleId: result.id
        }
      };
    } catch (error) {
      console.error('规则上传错误：', error);
      return {
        code: -1,
        message: '发布失败：' + error.message
      };
    }
  },

  /**
   * 更新规则内容
   * @param {object} params - 参数对象
   * @param {string} params.ruleId - 规则ID
   * @param {string} params.title - 规则标题
   * @param {string} params.content - 规则内容
   * @param {string} params.category - 规则分类
   * @param {string} params.subcategory - 规则子分类
   * @param {array} params.tags - 规则标签
   * @param {string} params.version - 规则版本
   * @param {string} params.language - 语言
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {string} params.documentFileID - 文档文件ID
   * @param {object} params.userInfo - 用户信息
   * @returns {object} 更新结果
   */
  async updateRuleContent(params) {
    try {
      const db = uniCloud.database();
      
      // 参数解构
      const { 
        ruleId,
        title, 
        content, 
        category, 
        subcategory, 
        tags, 
        version, 
        language, 
        userId, 
        token, 
        documentFileID,
        userInfo 
      } = params;
      
      // 验证必填参数
      if (!ruleId) {
        return {
          code: -1,
          message: '规则ID不能为空'
        };
      }
      
      if (!title || !content) {
        return {
          code: -1,
          message: '标题和内容为必填项'
        };
      }
      
      // 验证用户身份和token
      let currentUserId = '';
      let currentUserInfo = null;
      
      if (userId) {
        currentUserId = userId;
        currentUserInfo = userInfo;
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
            token: token
          });
          
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
            currentUserInfo = tokenRes.userInfo;
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }
      
      // 验证用户ID
      if (!currentUserId) {
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }
      
      // 查询规则信息
      const ruleResult = await db.collection('rule_contents').doc(ruleId).get();
      if (!ruleResult.data || ruleResult.data.length === 0) {
        return {
          code: -1,
          message: '规则不存在'
        };
      }
      
      const rule = Array.isArray(ruleResult.data) ? ruleResult.data[0] : ruleResult.data;
      
      // 检查权限
      if (rule.userId !== currentUserId && rule.creator_id !== currentUserId && rule.author_id !== currentUserId) {
        return {
          code: 403,
          message: '无权限修改此规则'
        };
      }
      
      // 准备更新数据
      const updateData = {
        title,
        content,
        category: category || '比赛规则',
        subcategory: subcategory || '',
        tags: Array.isArray(tags) ? tags : [],
        version: version || '1.0',
        language: language || 'zh-CN',
        update_date: new Date()
      };
      
      if (documentFileID) {
        updateData.document_url = documentFileID;
      }
      
      // 更新规则
      await db.collection('rule_contents').doc(ruleId).update(updateData);
      
      return {
        code: 0,
        message: '规则更新成功',
        data: {
          ruleId: ruleId
        }
      };
    } catch (error) {
      console.error('更新规则失败:', error);
      return {
        code: -1,
        message: '更新失败: ' + error.message
      };
    }
  },

  /**
   * 获取视频列表
   * @param {string} action - 操作类型
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} category - 分类
   * @param {string} keyword - 关键词
   * @param {string} creatorId - 创建者ID
   * @returns {object} 视频列表
   */
  async getVideoList(action = 'list', page = 1, limit = 10, category, keyword, creatorId) {
    const db = uniCloud.database();
    
    try {
      // 如果是获取管理员发布的视频
      if (action === 'getMyPublishedVideos' && creatorId) {
        return await this._getMyPublishedVideos(db, creatorId, page, limit, keyword, category);
      }
      
      // 构建查询条件
      const where = {};
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 添加关键词搜索
      if (keyword) {
        where.$or = [
          { title: db.command.regExp({ regexp: keyword, options: 'i' }) },
          { description: db.command.regExp({ regexp: keyword, options: 'i' }) }
        ];
      }
      
      // 只获取已发布的视频
      where.status = 'published';
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询视频列表
      const videosResult = await db.collection('learning_videos')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('learning_videos')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: videosResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取视频列表失败:', error);
      return {
        code: -1,
        message: '获取视频列表失败: ' + error.message
      };
    }
  },

  /**
   * 获取视频详情
   * @param {string} videoId - 视频ID
   * @returns {object} 视频详情
   */
  async getVideoDetail(videoId) {
    if (!videoId) {
      return {
        code: -1,
        message: '视频ID不能为空'
      };
    }

    try {
      const db = uniCloud.database();
      
      // 查询视频详情
      const videoResult = await db.collection('learning_videos')
        .doc(videoId)
        .get();
      
      if (!videoResult.data || videoResult.data.length === 0) {
        return {
          code: -1,
          message: '视频不存在'
        };
      }
      
      const videoData = Array.isArray(videoResult.data) ? videoResult.data[0] : videoResult.data;
      
      return {
        code: 0,
        message: '获取成功',
        data: videoData
      };
    } catch (error) {
      console.error('获取视频详情失败:', error);
      return {
        code: -1,
        message: '获取视频详情失败: ' + error.message
      };
    }
  },

  /**
   * 删除视频
   * @param {string} videoId - 视频ID
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 删除结果
   */
  async deleteVideo(videoId, userId, token) {
    try {
      const db = uniCloud.database();
      
      if (!videoId) {
        return {
          code: -1,
          message: '视频ID不能为空'
        };
      }
      
      // 验证用户权限
      let currentUserId;
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        const tokenResult = await db.collection('users').where({
          token: token
        }).get();
        
        if (tokenResult.data && tokenResult.data.length > 0) {
          currentUserId = tokenResult.data[0]._id;
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 查询视频信息
      const videoResult = await db.collection('learning_videos').doc(videoId).get();
      if (!videoResult.data || videoResult.data.length === 0) {
        return {
          code: -1,
          message: '视频不存在'
        };
      }
      
      const video = Array.isArray(videoResult.data) ? videoResult.data[0] : videoResult.data;
      
      // 检查权限
      if (video.userId !== currentUserId && video.creator_id !== currentUserId) {
        return {
          code: -1,
          message: '无权限删除此视频'
        };
      }
      
      // 软删除：更新状态为deleted
      await db.collection('learning_videos').doc(videoId).update({
        status: 'deleted',
        delete_date: new Date()
      });
      
      return {
        code: 0,
        message: '删除成功'
      };
    } catch (error) {
      console.error('删除视频失败:', error);
      return {
        code: -1,
        message: '删除失败: ' + error.message
      };
    }
  },

  /**
   * 上传视频内容
   * @param {string} title - 标题
   * @param {string} description - 描述
   * @param {string} video_url - 视频URL
   * @param {string} thumbnail - 缩略图
   * @param {string} category - 分类
   * @param {string} status - 状态
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 上传结果
   */
  async uploadVideoContent(title, description, video_url, thumbnail, category, status, userId, token) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      // 验证用户ID
      if (!currentUserId) {
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }
      
      // 验证必填参数
      if (!title || !video_url) {
        return {
          code: -1,
          message: '标题和视频URL为必填项'
        };
      }
      
      // 创建视频记录
      const videoData = {
        title,
        description: description || '',
        video_url,
        thumbnail: thumbnail || '',
        category: category || 'general',
        status: status || 'published',
        create_date: new Date(),
        update_date: new Date(),
        userId: currentUserId,
        creator_id: currentUserId,
        view_count: 0,
        duration: 0
      };
      
      const result = await db.collection('learning_videos').add(videoData);
      
      return {
        code: 0,
        message: '视频发布成功',
        data: {
          id: result.id
        }
      };
    } catch (error) {
      console.error('视频上传错误：', error);
      return {
        code: -1,
        message: '发布失败：' + error.message
      };
    }
  },

  /**
   * 添加学习记录
   * @param {string} resourceId - 资源ID
   * @param {string} resourceType - 资源类型（rule/video）
   * @param {string} userId - 用户ID
   * @param {number} progress - 学习进度
   * @param {number} duration - 学习时长
   * @returns {object} 添加结果
   */
  async addLearningRecord(resourceId, resourceType, userId, progress = 0, duration = 0) {
    try {
      const db = uniCloud.database();
      
      if (!resourceId || !resourceType || !userId) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 检查是否已有学习记录
      const existingRecord = await db.collection('learning_records')
        .where({
          user_id: userId,
          resource_id: resourceId,
          resource_type: resourceType
        })
        .get();
      
      if (existingRecord.data && existingRecord.data.length > 0) {
        // 更新现有记录
        const recordId = existingRecord.data[0]._id;
        await db.collection('learning_records').doc(recordId).update({
          progress: progress,
          duration: db.command.inc(duration),
          last_learn_time: new Date(),
          update_time: new Date()
        });
        
        return {
          code: 0,
          message: '学习记录更新成功'
        };
      } else {
        // 创建新记录
        const recordData = {
          user_id: userId,
          resource_id: resourceId,
          resource_type: resourceType,
          progress: progress,
          duration: duration,
          first_learn_time: new Date(),
          last_learn_time: new Date(),
          create_time: new Date(),
          update_time: new Date()
        };
        
        await db.collection('learning_records').add(recordData);
        
        return {
          code: 0,
          message: '学习记录添加成功'
        };
      }
    } catch (error) {
      console.error('添加学习记录失败:', error);
      return {
        code: -1,
        message: '添加学习记录失败: ' + error.message
      };
    }
  },

  /**
   * 获取学习进度
   * @param {string} userId - 用户ID
   * @param {string} resourceType - 资源类型（可选）
   * @returns {object} 学习进度
   */
  async getLearningProgress(userId, resourceType) {
    try {
      const db = uniCloud.database();
      
      if (!userId) {
        return {
          code: -1,
          message: '用户ID不能为空'
        };
      }
      
      // 构建查询条件
      const where = { user_id: userId };
      if (resourceType) {
        where.resource_type = resourceType;
      }
      
      // 查询学习记录
      const recordsResult = await db.collection('learning_records')
        .where(where)
        .orderBy('last_learn_time', 'desc')
        .get();
      
      return {
        code: 0,
        message: '获取成功',
        data: recordsResult.data || []
      };
    } catch (error) {
      console.error('获取学习进度失败:', error);
      return {
        code: -1,
        message: '获取学习进度失败: ' + error.message
      };
    }
  },

  /**
   * 保存学习进度
   * @param {string} userId - 用户ID
   * @param {string} resourceId - 资源ID
   * @param {string} resourceType - 资源类型
   * @param {number} progress - 进度
   * @param {number} duration - 学习时长
   * @returns {object} 保存结果
   */
  async saveLearningProgress(userId, resourceId, resourceType, progress, duration) {
    return await this.addLearningRecord(resourceId, resourceType, userId, progress, duration);
  },

  /**
   * 获取学习统计
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @returns {object} 学习统计
   */
  async getLearningStatistics({ userId, token } = {}) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 获取学习记录
      const recordsResult = await db.collection('learning_records')
        .where({ user_id: currentUserId })
        .get();
      
      const records = recordsResult.data || [];
      
      // 计算统计数据
      const totalCount = records.length;
      const completedCount = records.filter(record => record.progress >= 100).length;
      const totalDuration = records.reduce((sum, record) => sum + (record.duration || 0), 0);
      
      // 按资源类型统计
      const typeStats = {};
      records.forEach(record => {
        const type = record.resource_type || 'unknown';
        if (!typeStats[type]) {
          typeStats[type] = { total: 0, completed: 0, duration: 0 };
        }
        typeStats[type].total++;
        if (record.progress >= 100) {
          typeStats[type].completed++;
        }
        typeStats[type].duration += record.duration || 0;
      });
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          totalCount,
          completedCount,
          completionRate: totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0,
          totalDuration,
          typeStats
        }
      };
    } catch (error) {
      console.error('获取学习统计失败:', error);
      return {
        code: -1,
        message: '获取学习统计失败: ' + error.message
      };
    }
  },

  /**
   * 获取管理员发布的规则列表
   * @param {object} params - 参数对象
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @param {string} params.creatorId - 创建者ID
   * @param {string} params.keyword - 关键词
   * @param {string} params.category - 分类
   * @returns {object} 规则列表
   */
  async getMyadminRules(params) {
    try {
      const db = uniCloud.database();
      
      // 参数解构
      const { 
        page = 1, 
        limit = 10, 
        creatorId, 
        keyword, 
        category 
      } = params;
      
      if (!creatorId) {
        return {
          code: -1,
          message: '创建者ID不能为空'
        };
      }
      
      // 构建查询条件
      const where = {
        $or: [
          { creator_id: creatorId },
          { author_id: creatorId },
          { userId: creatorId }
        ],
        status: db.command.neq('deleted') // 排除已删除的规则
      };
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 添加关键词搜索
      if (keyword) {
        where.$and = where.$and || [];
        where.$and.push({
          $or: [
            { title: db.command.regExp({ regexp: keyword, options: 'i' }) },
            { content: db.command.regExp({ regexp: keyword, options: 'i' }) }
          ]
        });
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询规则列表
      const rulesResult = await db.collection('rule_contents')
        .where(where)
        .orderBy('create_date', 'asc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('rule_contents')
        .where(where)
        .count();
      
      // 处理结果数据
      const processedData = rulesResult.data.map(rule => {
        // 生成描述
        let description = rule.content ? rule.content.replace(/<[^>]*>/g, '') : '';
        if (description.length > 100) {
          description = description.substring(0, 100) + '...';
        }
        
        return {
          ...rule,
          createTime: rule.create_date,
          description: description || rule.title || '暂无描述',
          viewCount: rule.view_count || 0
        };
      });
      
      return {
        code: 0,
        message: '获取成功',
        data: processedData,
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取管理员规则列表失败:', error);
      return {
        code: -1,
        message: '获取规则列表失败: ' + error.message
      };
    }
  },

  /**
   * 生成规则描述
   * @param {string} content - 规则内容
   * @param {string} title - 规则标题
   * @returns {string} 描述
   */
  _generateDescription(content, title) {
    if (!content) {
      return title ? `${title} - 详细内容请点击查看` : '暂无描述';
    }
    
    // 去除HTML标签
    const plainText = content.replace(/<[^>]*>/g, '');
    
    // 截取前100个字符作为描述
    const maxLength = 100;
    if (plainText.length <= maxLength) {
      return plainText;
    }
    
    return plainText.substring(0, maxLength) + '...';
  },

  /**
   * 获取管理员发布的规则列表（私有方法）
   * @param {object} db - 数据库对象
   * @param {string} creatorId - 创建者ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} keyword - 关键词
   * @param {string} category - 分类
   * @param {string} subcategory - 二级分类
   * @returns {object} 规则列表
   */
  async _getMyPublishedRules(db, creatorId, page = 1, limit = 10, keyword, category, subcategory) {
    try {
      // 构建查询条件
      const where = {
        $or: [
          { userId: creatorId },
          { creator_id: creatorId }
        ]
      };
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({ regexp: keyword, options: 'i' });
      }
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 添加二级分类筛选
      if (subcategory && subcategory !== '全部') {
        where.subcategory = subcategory;
      }
      
      // 排除已删除的
      where.status = db.command.neq('deleted');
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询规则列表
      const rulesResult = await db.collection('rule_contents')
        .where(where)
        .field({
          _id: true,
          title: true,
          category: true,
          subcategory: true,
          tags: true,
          view_count: true,
          create_date: true,
          update_date: true,
          status: true,
          author_id: true,
          author_name: true
        })
        .orderBy('create_date', 'asc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('rule_contents')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: rulesResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取管理员发布的规则列表失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取管理员发布的视频列表（私有方法）
   * @param {object} db - 数据库对象
   * @param {string} creatorId - 创建者ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} keyword - 关键词
   * @param {string} category - 分类
   * @returns {object} 视频列表
   */
  async _getMyPublishedVideos(db, creatorId, page = 1, limit = 10, keyword, category) {
    try {
      // 构建查询条件
      const where = {
        $or: [
          { userId: creatorId },
          { creator_id: creatorId }
        ]
      };
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({ regexp: keyword, options: 'i' });
      }
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 排除已删除的
      where.status = db.command.neq('deleted');
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询视频列表
      const videosResult = await db.collection('learning_videos')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('learning_videos')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: videosResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取管理员发布的视频列表失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取最新资源（包括规则和视频）
   * @param {number} limit - 返回数量限制
   * @returns {object} 最新资源列表
   */
  async getLatestResources({ limit = 6 } = {}) {
    const db = uniCloud.database();
    
    try {
      // 获取最新规则
      const rulesResult = await db.collection('rule_contents')
        .where({
          status: 'published'
        })
        .orderBy('create_date', 'desc')
        .limit(Math.ceil(limit / 2))
        .field({
          _id: true,
          title: true,
          category: true,
          create_date: true,
          summary: true,
          view_count: true
        })
        .get();
      
      // 获取最新视频
      const videosResult = await db.collection('learning_videos')
        .orderBy('create_date', 'desc')
        .limit(Math.ceil(limit / 2))
        .field({
          _id: true,
          title: true,
          category: true,
          create_date: true,
          cover_image: true,
          view_count: true,
          duration: true
        })
        .get();
      
      // 合并结果并添加资源类型
      const resources = [];
      
      // 添加规则资源
      if (rulesResult.data && rulesResult.data.length > 0) {
        rulesResult.data.forEach(rule => {
          resources.push({
            ...rule,
            type: 'rule',
            resourceType: 'rule',
            url: `/packageStudy/study/rule-detail?id=${rule._id}`,
            thumbnail: rule.cover_image || '/static/images/rule-default.png'
          });
        });
      }
      
      // 添加视频资源
      if (videosResult.data && videosResult.data.length > 0) {
        videosResult.data.forEach(video => {
          resources.push({
            ...video,
            type: 'video',
            resourceType: 'video',
            url: `/packageStudy/study/video-detail?id=${video._id}`,
            thumbnail: video.cover_image || '/static/images/video-default.png'
          });
        });
      }
      
      // 按创建时间排序并限制数量
      resources.sort((a, b) => new Date(b.create_date) - new Date(a.create_date));
      const limitedResources = resources.slice(0, limit);
      
      return {
        code: 0,
        message: '获取成功',
        data: limitedResources
      };
    } catch (error) {
      console.error('获取最新资源失败:', error);
      return {
        code: -1,
        message: '获取最新资源失败: ' + error.message,
        data: []
      };
    }
  },

  /**
   * 获取学习统计信息
   * @param {string} userId - 用户ID
   * @returns {object} 学习统计数据
   */
  async getLearningStatisticsInfo(userId) {
    try {
      const db = uniCloud.database();
      
      if (!userId) {
        return {
          code: -1,
          message: '用户ID不能为空'
        };
      }
      
      // 获取学习记录
      const recordsResult = await db.collection('learning_records')
        .where({ user_id: userId })
        .get();
      
      const records = recordsResult.data || [];
      
      // 计算统计数据
      const totalResources = records.length;
      const completedResources = records.filter(record => record.progress >= 100).length;
      const totalDuration = records.reduce((sum, record) => sum + (record.duration || 0), 0);
      
      // 按资源类型统计
      const typeStats = {};
      records.forEach(record => {
        const type = record.resource_type || 'unknown';
        if (!typeStats[type]) {
          typeStats[type] = { total: 0, completed: 0, duration: 0 };
        }
        typeStats[type].total++;
        if (record.progress >= 100) {
          typeStats[type].completed++;
        }
        typeStats[type].duration += record.duration || 0;
      });
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          totalResources,
          completedResources,
          completionRate: totalResources > 0 ? Math.round((completedResources / totalResources) * 100) : 0,
          totalDuration,
          typeStats
        }
      };
    } catch (error) {
      console.error('获取学习统计信息失败:', error);
      return {
        code: -1,
        message: '获取学习统计信息失败: ' + error.message
      };
    }
  }
}; 